package com.qf.common;

import com.qf.utils.CustomException;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.SocketException;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.Map;

/**
 * @author : qinggang.liu voo@163.com
 * @ClassName com.yizhilu.os.core.util.web.HttpUtil
 * @description
 * @Create Date : 2014-4-15 下午12:51:53
 */
public class HttpClientUtil {

    private static final Logger logger = Logger.getLogger(HttpClientUtil.class);

    /**
     * 执行一个HTTP GET请求，返回请求响应的HTML
     *
     * @param url         请求的URL地址
     * @param queryString 请求的查询参数,可以为null
     * @return 返回请求响应的HTML
     */
    public static String doGet(String url, String queryString) {
        String response = null;
        HttpClient client = new HttpClient(new HttpClientParams(),new SimpleHttpConnectionManager(true) );
        HttpMethod method = new GetMethod(url);
        method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
        try {
            if (StringUtils.isNotBlank(queryString))
                method.setQueryString(URIUtil.encodeQuery(queryString));
            client.executeMethod(method);
            if (method.getStatusCode() == HttpStatus.SC_OK) {
                response = method.getResponseBodyAsString();
                System.out.println("---------------------------------------------------" + response);
            }
        } catch (ConnectException e) {
            System.out.println(new Date().getTime());
            throw new CustomException("连接超时");
        } catch (SocketException e) {
            throw new CustomException("连接超时");
        } catch (URIException e) {
            throw new CustomException("连接超时");
        } catch (IOException e) {
            throw new CustomException("连接失败");
        } finally {
            method.releaseConnection();
        }
        return response;
    }


    public static String doPostForJson(String url, JSONObject params) throws CustomException {
        HttpPost post = null;
        org.apache.http.client.HttpClient httpClient = null;
        try {
            httpClient  = new DefaultHttpClient();
            System.out.println(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
            post = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();//设置请求和传输超时时间
            post.setConfig(requestConfig);
            // 构造消息头
            post.setHeader("Content-type", "application/json; charset=utf-8");
            StringEntity entity = new StringEntity(params.toString(), Charset.forName("UTF-8"));
            entity.setContentEncoding("UTF-8");
            // 发送Json格式的数据请求
            entity.setContentType("application/json");
            post.setEntity(entity);
            HttpResponse response = httpClient.execute(post);
            // 检验返回码
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println("---------------------------------------------------" + statusCode);
            //{"code":0,"data":{"ip":"http://191.36.192.196:3128","id":338,"https":false}}
            if (statusCode != org.apache.http.HttpStatus.SC_OK) {
                System.out.println("-1");
            } else {
                HttpEntity result = response.getEntity();
                System.out.println(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
                return EntityUtils.toString(result);
            }
        } catch (ConnectException e) {
            System.out.println(new Date().getTime());
            throw new CustomException("连接超时");
        } catch (SocketException e) {
            throw new CustomException("连接超时");
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("连接失败");
        } finally {
            if (post != null) {
                post.releaseConnection();
                httpClient.getConnectionManager().shutdown();
            }
        }
        return "";
    }

    /**
     * 执行一个HTTP POST请求，返回请求响应的HTML
     *
     * @param url    请求的URL地址
     * @param params 请求的查询参数,可以为null
     * @return 返回请求响应的HTML
     */
    public static String doPost(String url, Map<String, String> params) {
        logger.debug("Post Url:" + url + ",Params:" + params);
        StringBuffer result = new StringBuffer();
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(url);
        method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
        // 设置Http Post数据
        if (!ObjectUtils.isNull(params)) {
            NameValuePair[] data = new NameValuePair[params.size()];
            int i = 0;
            for (Map.Entry<String, String> entry : params.entrySet()) {
                data[i++] = new NameValuePair(entry.getKey(), entry.getValue());
            }
            method.setRequestBody(data);

        }
        try {
            client.executeMethod(method);
            if (method.getStatusCode() == HttpStatus.SC_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8"));
                String str = null;
                while ((str = reader.readLine()) != null) {
                    result.append(str);
                }
            }
        } catch (IOException e) {
        } finally {
            method.releaseConnection();
        }
        logger.debug("Post Return:" + result.toString());
        return result.toString();
    }

    /**
     * 执行一个HTTP POST请求，返回请求响应的HTML
     *
     * @param url    请求的URL地址
     * @param params 请求的查询参数,可以为null
     * @return 返回请求响应的HTML
     */
    public static void doThreadPost(String url, Map<String, String> params) {
        HttpClientUtil httpUtil = new HttpClientUtil();
        HttpPostThread httpPostThread = httpUtil.new HttpPostThread(url, params);
        httpPostThread.start();
    }

    class HttpPostThread extends Thread {
        private String url;
        private Map<String, String> params;

        public HttpPostThread(String url, Map<String, String> params) {
            this.url = url;
            this.params = params;
        }

        @Override
        public void run() {
            doPost(url, params);
        }
    }

}
